package com.ta.util;


import com.ta.service.ex.FileNotFoundException;
import com.ta.service.ex.FileTypeException;
import com.ta.service.ex.FileUploadException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Component
public class UploadFile {
    @Value("${uploadfile.filetype}")
    private List<String> fileType;

    @Value("${uploadfile.filemax}")
    private Integer fileMax;

    public String uploadAvatar(MultipartFile file, String mkdirName, String fileName, HttpSession session){
        String path = session.getServletContext().getRealPath(mkdirName);
        File mkdir = new File(path);
        if(!mkdir.exists()){
            mkdir.mkdir();
        }

        if (file.isEmpty()){
            throw new FileNotFoundException("文件为空!");
        }

        String fileContentType = file.getContentType();
        if (!fileType.contains(fileContentType)) {
            throw new FileTypeException("文件类型异常,仅支持"+fileType);
        }

        if (file.getSize()>fileMax) {
            throw new FileTypeException("文件上限"+fileMax/1024/1024+"mb");
        }

        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        File uploadFile = new File(mkdir, fileName+suffix);
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            throw new FileUploadException("文件上传出现未知异常");
        }
        return "/"+mkdirName+"/"+fileName+suffix;
    }

}
